package com.pvj.myaccount

import android.R
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.DatePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.pvj.myaccount.databinding.ActivityAddCostBinding
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.room.entity.MonthCost
import com.pvj.myaccount.ui.home.HomeViewModel
import com.pvj.myaccount.ui.slideshow.MonthCostViewModel
import com.pvj.myaccount.uitls.TimeUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Calendar
import java.util.Date
import java.util.Locale

class AddActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {
    private val mTAG =  "AddActivity"

    private lateinit var binding: ActivityAddCostBinding
    private lateinit var slideshowViewModel: MonthCostViewModel
    private lateinit var homeViewModel: HomeViewModel

    private val items = arrayOf("生活用品", "饮食", "水果", "妇幼","房租", "话费/电信", "贷款", "交通出行", "其他")

    private var dataId: Int = -1

    private var curSelectTime: Long = -1L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddCostBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.setDisplayHomeAsUpEnabled(true);

        commonUI()

        val keyType = intent.getIntExtra(KeyConfig.KEY_TYPE, KeyConfig.TYPE_COST)
        if (keyType == KeyConfig.TYPE_COST) {
            costUI()
        } else {
            monthCostUI()
        }

        saveBtnClick(keyType)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        if (item.itemId == R.id.home) {
            // 处理返回键点击事件
            onBackPressedDispatcher.onBackPressed()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun commonUI() {
        // 创建ArrayAdapter，将数据源和布局资源传入
        val adapter = ArrayAdapter(this, R.layout.simple_spinner_item, items)
        // 设置下拉列表的布局样式（可选）
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        // 将适配器应用到Spinner
        binding.spinner.adapter = adapter

        binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                binding.otherText.visibility =
                    if (position == (items.size - 1)) View.VISIBLE else View.GONE
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有项被选中时调用
            }
        }
    }

    private fun costUI() {
        homeViewModel =
            ViewModelProvider(this)[HomeViewModel::class.java]
        supportActionBar?.title = "账单设置"
        binding.timeLayout.visibility = View.VISIBLE
        binding.autoInsertBtn.visibility = View.VISIBLE
        binding.timeBtn.setOnClickListener {
            val calendar = Calendar.getInstance(Locale.CHINA)
            val dialog = DatePickerDialog(
                this,
                this,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            dialog.show()
        }

        binding.autoInsertBtn.setOnClickListener {
            loadMonthData()
        }

        if (intent.hasExtra(KeyConfig.KEY_DATA)) {
            binding.autoInsertBtn.visibility = View.GONE

            val data: Cost =
                intent.getSerializableExtra(KeyConfig.KEY_DATA) as Cost
            dataId = data.id
            binding.nameText.setText(data.name)
            binding.moneyText.setText(data.money.toString())

            val index = items.indexOfFirst { it == data.type }
            if (index != -1) {
                binding.spinner.setSelection(index)
                binding.otherText.visibility = View.GONE
            } else {
                binding.spinner.setSelection(items.size - 1)
                binding.otherText.setText(data.type)
            }

            curSelectTime = data.eventTime
            binding.timeBtn.text = TimeUtil.timestampToBeijingStr(curSelectTime)

        }
    }

    private fun loadMonthData() {
        val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
        scope.launch {
            withContext(Dispatchers.IO) {
                val list = homeViewModel.loadMonthData()
                Log.d("HomeFragment", "all = " + list.toString());

                if (curSelectTime == -1L) {
                    curSelectTime = TimeUtil.getCurrentBeijingTimestamp()
                }

                list?.run {
                    for (item in list) {
                        val cost = Cost(
                            item.name,
                            item.money,
                            item.type, curSelectTime
                        )
                        cost.isRegular = 1
                        homeViewModel.insertAsync(cost)
                    }
                }

            }
            // 在这里更新UI线程
            withContext(Dispatchers.Main) {
                Toast.makeText(this@AddActivity, "一键保存成功", Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

    private fun monthCostUI() {
        slideshowViewModel =
            ViewModelProvider(this)[MonthCostViewModel::class.java]
        supportActionBar?.title = "月固定账单设置"

        if (intent.hasExtra(KeyConfig.KEY_DATA)) {
            val monthCost: MonthCost =
                intent.getSerializableExtra(KeyConfig.KEY_DATA) as MonthCost
            dataId = monthCost.id
            binding.nameText.setText(monthCost.name)
            binding.moneyText.setText(monthCost.money.toString())

            val index = items.indexOfFirst { it == monthCost.type }
            if (index != -1) {
                binding.spinner.setSelection(index)
                binding.otherText.visibility = View.GONE
            } else {
                binding.spinner.setSelection(items.size - 1)
                binding.otherText.setText(monthCost.type)
            }
        }


    }

    private fun saveBtnClick(keyType:Int){
        binding.saveBtn.setOnClickListener {
            val selectedPosition = binding.spinner.selectedItemPosition

            val type = if (selectedPosition != items.size - 1) {
                items[selectedPosition]
            } else {
                if (binding.otherText.text.isEmpty()) "" else binding.otherText.text.toString()
            }

            if (binding.nameText.text.isEmpty()) {
                Toast.makeText(this, "名称不能为空!!!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (binding.moneyText.text.isEmpty()) {
                Toast.makeText(this, "金额不能为空!!!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (keyType == KeyConfig.TYPE_COST) {
                costUIClick(type)
            } else {
                monthCostUIClick(type)
            }

            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()

            finish()
        }
    }

    private fun costUIClick(type:String){

        if (curSelectTime == -1L) {
            curSelectTime = TimeUtil.getCurrentBeijingTimestamp()
        }

        val cost = Cost(
            "${binding.nameText.text}",
            binding.moneyText.text.toString().toDouble(),
            type, curSelectTime
        )

        if (dataId != -1) {
            cost.id = dataId
            homeViewModel.updateAsync(
                cost
            )
        } else {
            homeViewModel.insertAsync(
                cost
            )
        }

        Log.d(mTAG, "costUIClick:${cost}")
    }

    private fun monthCostUIClick(type:String){
        if (dataId != -1) {
            val coast = MonthCost(
                "${binding.nameText.text}",
                binding.moneyText.text.toString().toDouble(),
                type
            )
            coast.id = dataId
            slideshowViewModel.updateAsync(
                coast
            )
        } else {
            slideshowViewModel.insertAsync(
                MonthCost(
                    "${binding.nameText.text}",
                    binding.moneyText.text.toString().toDouble(),
                    type
                )
            )
        }
    }


    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        val time = "${year}-${month + 1}-${dayOfMonth} 00:00"
        binding.timeBtn.text = time
        curSelectTime = TimeUtil.convertToDateTimestamp(year, month + 1, dayOfMonth)
    }
}